<template>
  <div class="chat-container">
    <div class="chat-content">
      <!-- 头部 -->
      <div class="chat-header">
        <div class="header-title">
          <span class="chat-title">与 {{ partnerName }} 的对话</span>
        </div>
        <el-button class="back-button" @click="handleBack" icon="el-icon-back">
          返回(Esc)
        </el-button>
      </div>

      <!-- 消息列表 -->
      <div class="message-list" ref="messageListRef">
        <div
          v-for="msg in messages"
          :key="msg.id"
          class="message-item"
          :class="{ 'message-self': msg.sender_id === currentUserId }"
        >
          <!-- 头像 -->
          <div class="avatar">
            <div
              class="avatar-text"
              :class="{ 'self-avatar': msg.sender_id === currentUserId }"
            >
              {{ msg.sender_id === currentUserId ? userInitial : partnerInitial }}
            </div>
          </div>
          <!-- 气泡 + 时间 -->
          <div class="message-wrapper">
            <div class="message-content">
              {{ msg.content }}
            </div>
            <div class="message-time">
              {{ formatTime(msg.created_at) }}
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区 -->
      <div class="message-input">
        <el-input
          v-model="newMessage"
          type="textarea"
          :rows="2"
          placeholder="请输入消息"
          @keyup.enter.ctrl="sendMessage"
          clearable
        />
        <el-button type="primary" @click="sendMessage">
          发送(Q)
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'

// 路由参数
const route = useRoute()
const router = useRouter()
const partnerId = ref(null)
const partnerName = ref('')
const houseId = ref(Number(route.query.house_id))
const fromUserCenter = ref(route.query.from_user_center === '1')
const activeTab = ref(route.query.active_tab || '')

// 登录信息
const currentUserId = ref(Number(localStorage.getItem('userId')))
const username = ref(localStorage.getItem('username') || '我')
const token = localStorage.getItem('token')

// 消息列表、新消息输入
const messages = ref([])
const newMessage = ref('')

// 加载状态控制
const loading = ref(false)
const page = ref(1)

// 消息列表滚动容器
const messageListRef = ref(null)

// 头像首字母计算属性
const userInitial = computed(() => username.value.charAt(0).toUpperCase())
const partnerInitial = computed(() => partnerName.value.charAt(0).toUpperCase())

// 加载消息历史
async function loadMessages() {
  if (loading.value) return
  loading.value = true

  try {
    const response = await axios.get('/chat/messages/history', {
      headers: { Authorization: `Bearer ${token}` },
      params: {
        user_id: currentUserId.value,
        partner_id: partnerId.value,
        page: 1,
        per_page: 20
      }
    })

    if (response.data.status === 200) {
      const { messages: fetchedMessages } = response.data.data
      const newMsgs = fetchedMessages.reverse()

      // 去重：只追加未出现的新消息
      const existingIds = new Set(messages.value.map(m => m.id))
      const filtered = newMsgs.filter(m => !existingIds.has(m.id))

      if (filtered.length > 0) {
        messages.value = [...messages.value, ...filtered]
        await nextTick()
        scrollToBottom()
      }
    } else {
      throw new Error(response.data.msg || '获取消息失败')
    }
  } catch (error) {
    console.error('获取消息失败:', error)
    ElMessage.error('获取消息失败')
  } finally {
    loading.value = false
  }
}

// 定时器引用
let refreshTimer = null

// 初始化
// 全局键盘事件处理函数
const handleKeydown = (e) => {
  // 处理Ctrl+Q快捷键
  if (e.ctrlKey && e.key === 'q') {
    e.preventDefault() // 阻止默认行为
    sendMessage()
  }
  
  // 处理Esc快捷键
  if (e.key === 'Escape') {
    e.preventDefault() // 阻止默认行为
    handleBack()
  }
}

onMounted(async () => {
  const userId = localStorage.getItem('userId')
  const token = localStorage.getItem('token')

  if (!userId || !token) {
    ElMessage.error('缺少必要信息')
    return
  }
  
  // 添加全局键盘事件监听
  window.addEventListener('keydown', handleKeydown)

  try {
    currentUserId.value = Number(userId)

    
    // 如果有 house_id，从房源详情页进入
    if (houseId.value) {
      const houseResponse = await axios.get(`/houses/getHouseDetails/${houseId.value}`, {
        headers: { Authorization: `Bearer ${token}` }
      })
      
      if (houseResponse.data.landlord_id) {
        partnerId.value = houseResponse.data.landlord_id
        partnerName.value = houseResponse.data.landlord_name
      } else {
        ElMessage.error('获取房东信息失败')
        return
      }
    } else {
      // 从消息列表进入，使用路由参数中的 partner_id
      partnerId.value = Number(route.query.partner_id)
      partnerName.value = route.query.partner_name || '未知用户'
    }

    await loadMessages()

    // 设置定时刷新 - 每30秒刷新一次消息
    refreshTimer = setInterval(async () => {
      await loadMessages()
    }, 30000) // 30000毫秒 = 30秒
   
  } catch (error) {
    console.error('初始化聊天失败:', error)
    ElMessage.error('获取信息失败')
  }
})

// 组件卸载时清理定时器和事件监听
onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
  
  // 移除全局键盘事件监听
  window.removeEventListener('keydown', handleKeydown)
})

async function sendMessage() {
  const content = newMessage.value.trim()
  if (!content) return

  try {
    const res = await axios.post(
      '/chat/messages/send',
      {
        user_id: currentUserId.value,
        receiver_id: partnerId.value,
        content
      },
      {
        headers: { Authorization: `Bearer ${token}` }
      }
    )

    if (res.data.status === 200) {
      messages.value.push({
        id: res.data.data.message_id,
        sender_id: currentUserId.value,
        content,
        created_at: new Date().toISOString()
      })
      newMessage.value = ''
      await nextTick()
      scrollToBottom()
      await loadMessages()
    } else {
      throw new Error(res.data.msg || '发送失败')
    }
  } catch (err) {
    console.error('发送消息失败:', err)
    ElMessage.error('发送消息失败：' + (err.message || '请稍后重试'))
  }
}

const formatTime = t => dayjs(t).format('YYYY-MM-DD HH:mm')

function scrollToBottom() {
  const el = messageListRef.value
  if (el) el.scrollTop = el.scrollHeight
}

// 处理返回按钮点击
const handleBack = () => {
  if (fromUserCenter.value) {
    // 如果是从用户中心来的，返回用户中心并带上activeTab参数
    router.push({
      path: '/user',
      query: { activeTab: activeTab.value }
    });
  } else {
    // 否则正常返回
    router.back();
  }
};
</script>

<style scoped>
.chat-container {
  height: 100vh;
  padding: 20px;
  background: #f5f5f5;
}

.chat-content {
  max-width: 1000px;
  margin: 0 auto;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
  height: calc(100vh - 40px);
}

.chat-header {
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title .chat-title {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.back-button {
  margin-left: auto;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.message-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  max-width: 70%;
}

.message-self {
  flex-direction: row-reverse;
  margin-left: auto;
}

.avatar {
  width: 40px;
  height: 40px;
  margin: 0 12px;
}

.avatar-text {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: #95ec69;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.self-avatar {
  background-color: #409EFF !important;
}

.message-wrapper {
  display: flex;
  flex-direction: column;
}

.message-content {
  padding: 12px 16px;
  background: #95ec69;
  color: #fff;
  border-radius: 15px 15px 15px 0;
  word-break: break-word;
  text-align: left;
}

.message-self .message-content {
  background: #e8f3ff;
  color: #000;
  border-radius: 15px 15px 0 15px;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin: 4px 0 0 4px;
}

.message-input {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 10px;
  background: #fafafa;
}
</style>
